package control
{
	import mx.containers.Panel;
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;
	import mx.rpc.events.ResultEvent;
	
	import org.puremvc.as3.interfaces.ICommand;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.command.SimpleCommand;
	
	import services.mainservice.MainService;
	
	import valueObjects.Contact;
	
	import view.ContactMediator;
	import view.ContactView;
	
	public class ContactCommand extends SimpleCommand implements ICommand
	{
		public static const CONTACT_COMMAND:String = "CONTACT_COMMAND";
		public static const ADD_CONTACT_OPEN:String = "ADD_CONTACT_OPEN";
		public static const EDIT_CONTACT_OPEN:String = "EDIT_CONTACT_OPEN";
		public static const DEL_CONTACT_OPEN:String = "DEL_CONTACT_OPEN";
		
		public function ContactCommand()
		{
			super();
		}
		
		override public function execute(notification:INotification):void {
			var mainApp:EasyMediator = this.facade.retrieveMediator(EasyMediator.EASY_MEDIATOR) as EasyMediator;
			switch(notification.getType()) {
				case ADD_CONTACT_OPEN:
					var createProject:Object = PopUpManager.createPopUp(mainApp.easyClient.operatorPanel,ContactView,false);
					this.facade.registerMediator(new ContactMediator(createProject));
					break;
				case EDIT_CONTACT_OPEN:
					var editContact:Object = PopUpManager.createPopUp(mainApp.easyClient.operatorPanel,ContactView,false);
					var obj:Object = notification.getBody();
					var contact:Contact = new Contact();
					contact.id = obj.id;
					contact.name = obj.label;
					contact.phone = obj.phone;
					contact.mail = obj.mail;
					this.facade.registerMediator(new ContactMediator(editContact,1,contact));
					break;
				case DEL_CONTACT_OPEN:
					var parent:Panel = (this.facade.retrieveMediator(EasyMediator.EASY_MEDIATOR) as EasyMediator).easyClient.operatorPanel;
					Alert.show("确定要删除"+notification.getBody().label+"吗","删除",Alert.OK|Alert.CANCEL,parent,onDel(notification.getBody().id));
					break;
			}
		}
		
		private function onDel(id:int):Function {
			var fun:Function = function(evt:CloseEvent):void {
				if(evt.detail == Alert.OK) {
					var service:MainService = new MainService();
					service.addEventListener(ResultEvent.RESULT,delFunction);
					service.delContact(id);
				}
			}
			return fun;
		}
		
		private function delFunction(evt:ResultEvent):void {
			var result:int = evt.result as int;
			if(result>0) {
				Alert.show("删除成功");
				this.sendNotification(EasyMediator.CHANGE_VIEW);
			}else {
				Alert.show("删除失败");
			}
		}
	}
}